import logging
import asyncio
import sys
import os

# 将项目根目录添加到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# 使用绝对导入
from config import NEWS_SOURCES, REDIS_CONFIG

try:
    import pyppeteer
    PYPPETEER_AVAILABLE = True
except ImportError:
    PYPPETEER_AVAILABLE = False
    logging.error("Pyppeteer不可用，无法获取cookies")

class CookieManager:
    def __init__(self, source_name=None):
        if not PYPPETEER_AVAILABLE:
            raise ImportError("Pyppeteer不可用，请先安装pyppeteer")
        
        # 从配置中获取URL
        self.url = self._get_url_from_config(source_name)
    
    def _get_url_from_config(self, source_name):
        """从配置文件中获取URL"""
        if not source_name:
            # 如果没有指定源，使用第一个
            return NEWS_SOURCES[0]['url'] if NEWS_SOURCES else 'https://www.mohrss.gov.cn/'
        
        # 查找指定的源
        for source in NEWS_SOURCES:
            if source['name'] == source_name:
                return source['url']
        
        # 如果找不到，使用默认值
        return 'https://www.mohrss.gov.cn/'
    
    def get_fresh_cookies(self):
        """获取cookies"""
        logging.info(f"开始获取cookies，URL: {self.url}")
        return asyncio.get_event_loop().run_until_complete(self.get_cookies_with_pyppeteer())
    
    async def get_cookies_with_pyppeteer(self):
        """使用Pyppeteer获取cookies"""
        logging.info(f"使用Pyppeteer获取cookies: {self.url}")
        
        # 启动浏览器
        browser = await pyppeteer.launch({
            'headless': True,
            'args': ['--no-sandbox', '--disable-setuid-sandbox']
        })
        
        try:
            # 打开新页面
            page = await browser.newPage()
            
            # 设置用户代理
            await page.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:137.0) Gecko/20100101 Firefox/137.0')
            
            # 访问网站
            await page.goto(self.url, {'waitUntil': 'networkidle0'})
            # 等待页面加载完成
            await page.waitForSelector('body', timeout=10000)
            
            # 获取cookies
            cookies_list = await page.cookies()
            cookies = {}
            for cookie in cookies_list:
                cookies[cookie['name']] = cookie['value']
            
            logging.info(f"成功获取cookies: {cookies}")
            return cookies
            
        except Exception as e:
            logging.error(f"Pyppeteer获取cookies失败: {str(e)}")
            raise
        finally:
            await browser.close()